//
//  TakeViewController.m
//  SweetComics
//
//  Created by LeeZhe on 15/1/28.
//  Copyright (c) 2015年 LeeZhe. All rights reserved.
//

#import "TakeViewController.h"
#import "SearchViewController.h"
#import "DataBaseHandler.h"
#import "DetailViewController.h"
#import "ComicsListCell.h"
#import "CollectTableViewCell.h"
#import "AFHTTPRequestOperationManager.h"
@interface TakeViewController ()<UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UIScrollView *scrollView;
@property (nonatomic, retain) UISegmentedControl *seg;
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UITableView *tableView2;
@property (nonatomic, retain) NSMutableArray *arr;

@end

@implementation TakeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 订阅的标题
    self.seg = [[UISegmentedControl alloc] initWithItems:@[@"订阅", @"浏览记录"]];
    self.navigationItem.titleView = self.seg;
    // 默认seg的选项
    self.seg.selectedSegmentIndex = 0;
    [self.seg addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
//    self.navigationController.navigationBar.barTintColor = [UIColor orangeColor];
//    self.navigationController.navigationBar.barTintColor = [UIColor colorWithHue:0.67 saturation:1 brightness:1 alpha:0.46];
//    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    

    
    self.dbHandler = [DataBaseHandler shareInstance];
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height)];
    _scrollView.contentSize = CGSizeMake(self.view.frame.size.width * 2, 0);
    [self.view addSubview:self.scrollView];
    _scrollView.bounces = NO;
    _scrollView.pagingEnabled = YES;
    _scrollView.scrollEnabled = YES;
    self.scrollView.delegate = self;
    [_scrollView release];
    
    self.arr = [NSMutableArray array];
    self.arr = [self.dbHandler selectCollect];
    self.temp = 2;
    [self createView];
    [_scrollView addSubview:_tableView];
    
}
// 搜索按钮
- (void)barButtonAction1:(UIBarButtonItem *)button
{
    self.hidesBottomBarWhenPushed = YES;
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
    [searchVC release];
}
// seg绑定的方法
- (void)segmentAction:(UISegmentedControl *)seg
{
    [self setEditing:NO animated:YES];
    NSInteger Index = seg.selectedSegmentIndex;
    NSLog(@"Index %ld", (long)Index);
    switch (Index) {
        case 0:
        {
            self.navigationItem.rightBarButtonItem = self.editButtonItem;
            self.arr = [self.dbHandler selectCollect];
            self.scrollView.contentOffset = CGPointMake(0, 0);
            self.tableView.frame = CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64 - 49);
            self.tableView.hidden = NO;
            self.tableView2.hidden = YES;
            [self.tableView reloadData];
            break;
        }
        case 1:
        {
            self.navigationItem.rightBarButtonItem = self.editButtonItem;
            self.arr = [self.dbHandler selectAll];
            self.scrollView.contentOffset = CGPointMake(self.view.frame.size.width, 0);
            self.tableView2 = [[UITableView alloc] initWithFrame:CGRectMake(self.view.frame.size.width, 64, self.view.frame.size.width, self.view.frame.size.height - 64 - 49) style:UITableViewStylePlain];
            self.tableView2.delegate = self;
            self.tableView2.dataSource = self;
            self.tableView2.separatorStyle = UITableViewCellSeparatorStyleNone;
            [self.scrollView addSubview:self.tableView2];
            self.tableView.hidden = YES;
            self.tableView2.hidden = NO;
            [self.tableView2 reloadData];
            break;
        }
        default:
            break;
    }
}

- (void)createView
{
    self.arr = [self.dbHandler selectCollect];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width,  self.view.frame.size.height - 64 - 49) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[[UITableView alloc] init] autorelease];
    //    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

#pragma mark - scrollView 的协议方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // 当scrollView滚动的时候, 就会调用这个方法
    // 1. 通过偏移量计算当前的页数
    
    NSInteger page = _scrollView.contentOffset.x / self.view.frame.size.width;
    // 2. 给seg赋值
    //    NSLog(@"====%ld", page);
    self.seg.selectedSegmentIndex = page;
    
}

- (void)setComicList:(ComicList *)comics
{
    NSString *str = [NSString stringWithFormat:@"http://mobilev3.ac.qq.com/Search/comicSearchListForIos/key_word/%@/listcnt/12/page/1/clientType/0", comics.title];
    NSLog(@"%@", str);
    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = responseObject;
        DetailViewController *detailVC = [[DetailViewController alloc] init];
        NSDictionary *dic1 = [[dic objectForKey:@"data"] firstObject];
        ComicList *comic = [[ComicList alloc] init];
        [comic setValuesForKeysWithDictionary:dic1];
        //        NSLog(@"====%@", comic);
        if (comic.title) {
            detailVC.comic = comic;
            [self.navigationController pushViewController:detailVC animated:YES];
            [detailVC release];
        }else
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"对不起,没有搜到你要找的漫画" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            [alert release];
            [detailVC release];
        }
        [self.tableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (self.seg.selectedSegmentIndex) {
        case 0:
        {
            self.arr = [self.dbHandler selectCollect];
            ComicList *comics = [self.arr objectAtIndex:indexPath.row];
            [self setComicList:comics];
        }
            break;
        case 1:
        {
            self.arr = [self.dbHandler selectAll];
            ComicList *comics = [self.arr objectAtIndex:indexPath.row];
            [self setComicList:comics];
        }
            break;
        default:
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (self.seg.selectedSegmentIndex) {
        case 0:
        {
            return 60;
        }
            break;
        case 1:
        {
            return 140;
        }
            break;
        default:
            return 0;
            break;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (self.seg.selectedSegmentIndex) {
        case 0:
        {
            self.arr = [self.dbHandler selectCollect];
            ComicList *comics = [self.arr objectAtIndex:indexPath.row];
            static NSString *one = @"one";
            UITableViewCell *cellOne = [tableView dequeueReusableCellWithIdentifier:one];
            if (!cellOne) {
                cellOne = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:one] autorelease];
            }
            cellOne.textLabel.text = comics.title;
            cellOne.textLabel.font = [UIFont systemFontOfSize:19];
            return cellOne;
            
        }
            break;
        case 1:
        {
            self.arr = [self.dbHandler selectAll];
//            NSLog(@"=====%@" ,self.arr);
            ComicList *comic = [self.arr objectAtIndex:indexPath.row];
            static NSString *cell2 = @"SecondCell";
            CollectTableViewCell *secondCell = [tableView dequeueReusableCellWithIdentifier:cell2];
            if (secondCell == nil) {
                secondCell = [[[CollectTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cell2] autorelease];
            }
            [secondCell setComics:comic];
            return secondCell;
        }
            break;
            
        default:
        {
            
            NSString *str = [NSString stringWithFormat:@"str%ld", (long)indexPath.row];
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
            if (cell == nil) {
                cell = [[[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier:str] autorelease];
            }
            
            return cell;
        }
            break;
    }
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (self.seg.selectedSegmentIndex) {
        case 0:
        {
            self.arr = [self.dbHandler selectCollect];
            return self.arr.count;
        }
            break;
        case 1:
        {
            self.arr = [self.dbHandler selectAll];
            return self.arr.count;
        }
            break;
        default:
            return 0;
            break;
    }
}

// 改变编辑方式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}
// 删除
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    // 每当点击系统的而编辑按钮的时候, 就会调用这个方法;
    switch (self.seg.selectedSegmentIndex) {
        case 0:
        {
            
            self.tableView.hidden = NO;
            self.tableView2.hidden =YES;
            [self.tableView reloadData];
            [super setEditing:editing animated:animated];
            [_tableView setEditing:editing animated:animated];
            NSLog(@"%d", editing);
//            editing = 0;
        }
            break;
        case 1:
        {
            self.tableView.hidden = YES;
            self.tableView2.hidden = NO;
            [self.tableView2 reloadData];
            [super setEditing:editing animated:animated];
            [_tableView2 setEditing:editing animated:animated];
            NSLog(@"%d", editing);
//            editing = 0;
        }
            break;
        default:
            
            break;
    }
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (self.seg.selectedSegmentIndex) {
        case 0:
        {
            if (editingStyle == UITableViewCellEditingStyleDelete) {
                self.arr = [self.dbHandler selectCollect];
                ComicList *comic = [self.arr objectAtIndex:indexPath.row];
                [self.dbHandler deleteCollect:comic];
                [self.arr removeObjectAtIndex:indexPath.row];
                [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
                
            }
        }
            break;
        case 1:
        {
            if (editingStyle == UITableViewCellEditingStyleDelete) {
                self.arr = [self.dbHandler selectAll];
                ComicList *comic = [self.arr objectAtIndex:indexPath.row];
                [self.dbHandler deleteComic:comic];
                [self.arr removeObjectAtIndex:indexPath.row];
                [_tableView2 deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
                
            }
        }
            break;
        default:
            break;
    }
}


- (void)dealloc
{
    [_view1 release];
    [_view2 release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
